package com.openvid.webrtc

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast

/**
 * @author jinyf
 */
object ToastUtil {

    private val context: Context
        get() = getC()

    @JvmStatic
    fun show(resId: Int) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show()
    }

    @JvmStatic
    fun show(res: String?) {
        Toast.makeText(context, res, Toast.LENGTH_SHORT).show()
    }

    @JvmStatic
    fun showLong(resId: Int) {
        Toast.makeText(context, resId, Toast.LENGTH_LONG).show()
    }

    @JvmStatic
    fun showLong(str: String?) {
        Toast.makeText(context, str, Toast.LENGTH_LONG).show()
    }

    @JvmStatic
    fun showInThread(desc: String?) {
        val handler = Handler(Looper.getMainLooper())
        handler.post { show(desc) }
    }

    private var CONTEXT_INSTANCE: Context? = null

    fun getC(): Context {
        if (CONTEXT_INSTANCE == null) {
            synchronized(ToastUtil::class.java) {
                if (CONTEXT_INSTANCE == null) {
                    try {
                        val ActivityThread =
                            Class.forName("android.app.ActivityThread")
                        val method =
                            ActivityThread.getMethod("currentActivityThread")
                        val currentActivityThread = method.invoke(ActivityThread)
                        val method2 =
                            currentActivityThread.javaClass.getMethod("getApplication")
                        CONTEXT_INSTANCE =
                            method2.invoke(currentActivityThread) as Context
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
        return CONTEXT_INSTANCE!!
    }
}